package com.devtools.project.tool.datasource.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.devtools.common.utils.poi.ExcelUtil;
import com.devtools.common.utils.text.Convert;
import com.devtools.framework.aspectj.lang.annotation.Log;
import com.devtools.framework.aspectj.lang.enums.BusinessType;
import com.devtools.framework.web.controller.BaseController;
import com.devtools.framework.web.domain.AjaxResult;
import com.devtools.framework.web.page.TableDataInfo;
import com.devtools.project.tool.datasource.domain.DataTable;
import com.devtools.project.tool.datasource.domain.DataTableQuery;
import com.devtools.project.tool.datasource.domain.ToolDatasource;
import com.devtools.project.tool.datasource.service.IDatasourceService;
import com.devtools.project.tool.gen.domain.GenConfigVo;
import com.devtools.project.tool.swagger.service.WordService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.List;

/**
 * 数据源信息操作处理
 *
 * @author devtools
 * @date 2022-11-28
 */
@Controller
@RequestMapping("/tool/datasource")
public class DatasourceController extends BaseController {
    private String prefix = "/tool/datasource";
    @Autowired
    private WordService wordService;
    @Autowired
    private IDatasourceService datasourceService;

    @RequestMapping(value = "{datasourceId}/doc", method = {RequestMethod.GET})
    public String view(Model model, @PathVariable("datasourceId") Integer datasourceId) {
        DataTableQuery query=new DataTableQuery();
        query.setDatasourceId(datasourceId);
        JSONObject result = datasourceService.wordData(query);
        model.addAttribute("download", 1);
        model.addAllAttributes(result);
        return result.getString("template");
    }
    @RequestMapping(value = "/viewDoc", method = {RequestMethod.GET})
    public String viewDoc(Model model, DataTableQuery query) {
        JSONObject result = datasourceService.wordData(query);
        model.addAttribute("download", 1);
        model.addAllAttributes(result);
        return result.getString("template");
    }
    /**
     * 将 swagger 文档一键下载为 doc 文档
     */
    @RequestMapping(value = "/downloadWord", method = {RequestMethod.GET})
    public void word(Model model, DataTableQuery query, HttpServletResponse response) {
        JSONObject data = datasourceService.wordData(query);
        model.addAllAttributes(data);
        model.addAttribute("download", 0);
        wordService.writeContentToResponse(model, data.getString("template"), data.getString("docName"), response);
    }

    @RequiresPermissions("tool:datasource:view")
    @GetMapping()
    public String datasource() {
        return prefix + "/datasource";
    }

    @GetMapping("table")
    public String table() {
        return prefix + "/table";
    }

    @GetMapping("tableGen")
    public String tableGen() {
        return prefix + "/tableGen";
    }

    /**
     * 批量生成代码
     */
    @PostMapping("/batchGenCode")
    @ResponseBody
    public AjaxResult batchGenCode(GenConfigVo vo) throws Exception
    {
       byte[] data= datasourceService.generatorCode(vo);
       String temp="devtools"+System.currentTimeMillis()+".zip";
        OutputStream out  = new FileOutputStream(ExcelUtil.getAbsoluteFile(temp));
        out.write(data);
        out.close();
        return AjaxResult.success(temp);
    }

    /**
     * 查询数据源列表
     */
    @RequiresPermissions("tool:datasource:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(ToolDatasource datasource) {
        startPage();
        QueryWrapper<ToolDatasource> queryWrapper = new QueryWrapper<ToolDatasource>(datasource);
        List<ToolDatasource> list = datasourceService.list(queryWrapper);
        return getDataTable(list);
    }

    @PostMapping("/tableList")
    @ResponseBody
    public TableDataInfo listTable(DataTableQuery query) {
        startPage();
        List<DataTable> list = datasourceService.getDataTableList(query);
        return getDataTable(list);
    }

    /**
     * 导出数据源列表
     */
    @RequiresPermissions("tool:datasource:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(ToolDatasource datasource) {
        QueryWrapper<ToolDatasource> queryWrapper = new QueryWrapper<ToolDatasource>(datasource);
        List<ToolDatasource> list = datasourceService.list(queryWrapper);
        ExcelUtil<ToolDatasource> util = new ExcelUtil<ToolDatasource>(ToolDatasource.class);
        return util.exportExcel(list, "datasource");
    }

    /**
     * 新增数据源
     */
    @GetMapping("/add")
    public String add() {
        return prefix + "/add";
    }

    /**
     * 新增保存数据源
     */
    @RequiresPermissions("tool:datasource:add")
    @Log(title = "数据源", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(ToolDatasource datasource) {
        return toAjax(datasourceService.save(datasource) ? 1 : 0);
    }

    /**
     * 修改数据源
     */
    @GetMapping("/edit/{datasourceId}")
    public String edit(@PathVariable("datasourceId") Integer datasourceId, ModelMap mmap) {
        ToolDatasource datasource = datasourceService.getById(datasourceId);
        mmap.put("datasource", datasource);
        return prefix + "/edit";
    }

    /**
     * 修改保存数据源
     */
    @RequiresPermissions("tool:datasource:edit")
    @Log(title = "数据源", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(ToolDatasource datasource) {
        return toAjax(datasourceService.updateById(datasource) ? 1 : 0);
    }

    /**
     * 删除数据源
     */
    @RequiresPermissions("tool:datasource:remove")
    @Log(title = "数据源", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        List<Integer> lst = Arrays.asList(Convert.toIntArray(ids));
        return toAjax(datasourceService.removeByIds(lst) ? 1 : 0);
    }

}
